package educrypt.database.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map.Entry;

import educrypt.database.Connector;
import educrypt.filter.Equivalences;

public class EquivalencesDAO {

	/* Singleton */
	private EquivalencesDAO() {
	}

	public static EquivalencesDAO getInstance() {
		return SingletonHolder.instance;
	}

	private static class SingletonHolder {
		public static final EquivalencesDAO instance = new EquivalencesDAO();
	}

	/* END Singleton */

	public Equivalences findEquivalences() {
		String sqlGetEquivalences = "SELECT * FROM Equivalences";
		Equivalences equivalences = new Equivalences();
		try {
			Connection conn = Connector.getConnection();
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sqlGetEquivalences);
			while (rs.next()) {
				char symbol = rs.getString("symbol").charAt(0);
				char equivalent = rs.getString("equivalent").charAt(0);
				equivalences.addEquivalence(symbol, equivalent);
			}
			rs.close();
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return equivalences;
	}

	public void createEquivalences(Equivalences equivalences) {
		String sqlCreateEquivalences = "MERGE INTO Equivalences (symbol,equivalent) VALUES (?,?)";
		try {
			Connection conn = Connector.getConnection();
			PreparedStatement ps = conn.prepareStatement(sqlCreateEquivalences);
			for (Entry<Character, Character> equivalencePair : equivalences) {
				ps.setString(1, equivalencePair.getKey().toString());
				ps.setString(2, equivalencePair.getValue().toString());
				ps.addBatch();
			}
			ps.executeBatch();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
